package com.xzx.flink.streamapi.transform;

import com.xzx.flink.bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2021-08-24 11:11 下午
 */
public class Transform_04_KeyBy {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> streamSource = env.readTextFile("/Users/xinzhixuan/work/git/flink-study-java/src/main/resources/sensor.txt");
        SingleOutputStreamOperator<SensorReading> map = streamSource.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String value) throws Exception {
                String[] split = value.split(" ");
                return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
            }
        });

        KeyedStream<SensorReading, String> keyBy = map.keyBy(SensorReading::getId);
        keyBy.print("keyBy");

        SingleOutputStreamOperator<SensorReading> sum = keyBy.sum("temperature");
        sum.print("sum");

        SingleOutputStreamOperator<SensorReading> max = keyBy.max("temperature");
        max.print("max");//除temperature字段外，其他字段都是第一条数据的值

        SingleOutputStreamOperator<SensorReading> min = keyBy.min("temperature");
        min.print("min");

        SingleOutputStreamOperator<SensorReading> minBy = keyBy.minBy("temperature");
        minBy.print("minBy");

        SingleOutputStreamOperator<SensorReading> maxBy = keyBy.maxBy("temperature");
        maxBy.print("maxBy");//temperature为最大值的整条数据


        env.execute(Transform_04_KeyBy.class.getName());
    }
}
